home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 7 / Apprentice-Release7.iso / Source Code / C / Applications / Moscow ML 1.42 / examples / lexyacc / Main.sml < prev    next >
Encoding:
Text File  |  1997-08-18  |  1.6 KB  |  57 lines  |  [TEXT/R*ch]

  1. (* Main.sml : mosmllex and mosmlyac example *)
  2.  
  3. (* Parse *)
  4.  
  5. fun parseExprPlain file stream lexbuf =
  6.     let val expr = Parser.Main Lexer.Token lexbuf
  7.     in
  8.     Parsing.clearParser();
  9.     expr
  10.     end
  11.     handle exn => (Parsing.clearParser(); raise exn);
  12.  
  13. (* Parse; show offending program piece on error *)
  14.  
  15. fun parseExprReport file stream lexbuf =
  16.     let val expr = 
  17.         Parser.Main Lexer.Token lexbuf
  18.         handle
  19.            Parsing.ParseError f =>
  20.            let val pos1 = Lexing.getLexemeStart lexbuf
  21.                val pos2 = Lexing.getLexemeEnd lexbuf
  22.            in
  23.                Location.errMsg (file, stream, lexbuf) 
  24.                                (Location.Loc(pos1, pos2))
  25.                                "Syntax error."
  26.            end
  27.          | Lexer.LexicalError(msg, pos1, pos2) =>
  28.            if pos1 >= 0 andalso pos2 >= 0 then
  29.                Location.errMsg (file, stream, lexbuf)
  30.                                (Location.Loc(pos1, pos2))
  31.                                ("Lexical error: " ^ msg)
  32.            else 
  33.                (Location.errPrompt ("Lexical error: " ^ msg ^ "\n\n");
  34.             raise Fail "Lexical error");
  35.     in
  36.     Parsing.clearParser();
  37.     expr
  38.     end
  39.     handle exn => (Parsing.clearParser(); raise exn);
  40.  
  41. (* Create lexer from instream *)
  42.  
  43. fun createLexerStream (is : BasicIO.instream) =
  44.   Lexing.createLexer (fn buff => fn n => Nonstdio.buff_input is buff 0 n)
  45.  
  46. (* Parse a program from a file *)
  47.  
  48. fun parse file =
  49.     let val is     = Nonstdio.open_in_bin file
  50.         val lexbuf = createLexerStream is
  51.     val expr   = parseExprReport file is lexbuf
  52.                  handle exn => (BasicIO.close_in is; raise exn)
  53.     in 
  54.         BasicIO.close_in is;
  55.     expr
  56.     end
  57.